package pl.edu.agh.student.todo;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.appengine.api.capabilities.CapabilitiesService;
import com.google.appengine.api.capabilities.CapabilitiesServiceFactory;
import com.google.appengine.api.capabilities.Capability;
import com.google.appengine.api.capabilities.CapabilityStatus;

import pl.edu.agh.student.todo.dao.Dao;
import pl.edu.agh.student.todo.model.Todo;


public class NotificationServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7123997709656079424L;

	private static final Logger log = Logger.getLogger(EmailServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		log.info("Notify by email");
		
		CapabilitiesService service = CapabilitiesServiceFactory.getCapabilitiesService();
		CapabilityStatus status = service.getStatus(Capability.MAIL).getStatus();
		
		if (status == CapabilityStatus.ENABLED) {

			Date time = new Date();
			List<Todo> todos = Dao.INSTANCE.getTodos(time);
			System.out.println("TODO: "+todos);
			System.out.println("TODO: "+todos.size());
			
			for(Todo todo: todos){		
			
				Properties props = new Properties();
		        Session session = Session.getDefaultInstance(props, null);
		
		        String msgBody = "...";
		        String msgSubject = "jakis tytul";
		
		        String to = "jan.burkot@gmail.com";
		        try {
		            Message msg = new MimeMessage(session);
		            msg.setFrom(new InternetAddress("cron@sg-todos.appspotmail.com", "Cron"));
		            msg.addRecipient(Message.RecipientType.TO,
		                             new InternetAddress(to));
		            msg.setSubject(msgSubject);
		            msg.setText(msgBody);
		            Transport.send(msg);
		
		        } catch (AddressException e) {
		            // ...
		        	log.warning(e.getMessage());
		        } catch (MessagingException e) {
		            // ...
		        	log.warning(e.getMessage());
		        }

			Dao.INSTANCE.updateSent(todo.getId(), true);
		}
		}
	}
}
